package com.naizhuai.ui.mianbusiness.action;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.naizhuai.MainActivity;
import com.naizhuai.R;
import com.naizhuai.network.exception.ApiException;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.adapter.business.ActionAddImageAdapterHolder;
import com.naizhuai.ui.adapter.business.ActionBrightPointImageAdapterHolder;
import com.naizhuai.ui.adapter.business.ActionImageBrightPointProcessAdapterHolder;
import com.naizhuai.ui.entity.ImageBean;
import com.naizhuai.ui.entity.SimpleKeyValueBean;
import com.naizhuai.ui.entity.mainbusiness.ActionCompareDataBean;
import com.naizhuai.ui.entity.mainbusiness.ActionEditContractActivityBean;
import com.naizhuai.ui.entity.mainbusiness.ActionSelectedProcessImageDetails;
import com.naizhuai.ui.entity.mainbusiness.ActionSubmitScanDetailsBean;
import com.naizhuai.ui.entity.mainbusiness.CompareImageBean;
import com.naizhuai.ui.entity.management.CompanyBean;
import com.naizhuai.ui.loopviewpager.AutoLoopViewPager;
import com.naizhuai.ui.mianbusiness.action.presenter.ActionManageApiStoreIml;
import com.naizhuai.ui.mianbusiness.action.presenter.UploadImageApiStoreIml;
import com.naizhuai.ui.mianbusiness.setting.ThankSettingPagerActivity;
import com.naizhuai.ui.viewpagerindicator.CirclePageIndicator;
import com.naizhuai.util.ActivityStackManager;
import com.naizhuai.util.BitmapUtils;
import com.naizhuai.util.ConstantsState;
import com.naizhuai.util.DeviceUtils;
import com.naizhuai.util.DialogUtils;
import com.naizhuai.util.FileUtils;
import com.naizhuai.util.IntentUtils;
import com.naizhuai.util.ListUtils;
import com.naizhuai.util.MathUtils;
import com.naizhuai.util.NaizhuAILog;
import com.naizhuai.util.RxBus;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 浏览行为的详情界面界面
 */
public class ActionScanDetailsViewActivity extends BaseActivity implements View.OnClickListener, ActionBrightPointImageAdapterHolder.OnItemClickListener {
    private static final String TAG = "ActionScanDetailsViewActivity";

    private static final int TYPE_SUBMIT = 1000;
    private static final int TYPE_THANK = 1001;


    //改善title
    @BindView(R.id.action_name)
    TextView changeData;

    //展示合成图片的循环展示的图片集合
    @BindView(R.id.edit_pager)
    AutoLoopViewPager editPager;
    @BindView(R.id.edit_indicator)
    CirclePageIndicator circleIndicator;
    private List<Bitmap> editBitmaps;

    //数据展示
    @BindView(R.id.compare_data_card)
    CardView compareDataCard;
    @BindView(R.id.before_data)
    TextView preData;
    @BindView(R.id.b_value_count_type)
    TextView beforeValueType;
    @BindView(R.id.after_data)
    TextView aftData;
    @BindView(R.id.a_value_count_type)
    TextView afterValueType;
    @BindView(R.id.improve_ratio)
    TextView proRatio;
    //    @BindView(R.id.improve_money)
//    TextView proMoney;
    @BindView(R.id.b_value_layout)
    LinearLayout bValueLayout;
    @BindView(R.id.a_value_layout)
    LinearLayout aValueLayout;

    //分析
    @BindView(R.id.analysis_layout)
    CardView analysisLayout;
    @BindView(R.id.analysis_txt)
    RecyclerView analysisRecy;
    List<String> analysisList;
    private ActionImageBrightPointProcessAdapterHolder analysisAdapter;

    //过程数据集合
    @BindView(R.id.process_lines_txt)
    RecyclerView recyclerProTxt;
    @BindView(R.id.process_images)
    RecyclerView recyclerProImg;
    private List<String> processStr;
    private List<String> processImg;
    @BindView(R.id.process_details_layout)
    CardView detailLayout;

    private ActionSelectedProcessImageDetails imageDetails;
    //过程图片+过程描述的adapter
    private ActionBrightPointImageAdapterHolder imageContentAdapter;
    private ActionImageBrightPointProcessAdapterHolder detailsAdapter;

    //心得
    @BindView(R.id.action_experience)
    TextView experience;
    @BindView(R.id.review_card)
    CardView reviewCaed;


    private ActionSubmitScanDetailsBean scanDetailsBean;

    private int finishMergeCount = 0;
    private int bitmapChangeCount = 0;

    private ActionEditContractActivityBean editActivityBean;
    private EditContractPagerAdapter targetAdapter;
    private List<String> filePaths;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBaseData();
        initBaseView();
    }


    private void initBaseView() {
        recyclerProImg.post(new Runnable() {
            @Override
            public void run() {
                initRecyclerView();
                getDataFromRx();
            }
        });
    }

    private void initRecyclerView() {
        //过程分析数据
        analysisAdapter = new ActionImageBrightPointProcessAdapterHolder(this, analysisList);
        analysisRecy.setNestedScrollingEnabled(false);
        analysisRecy.setHasFixedSize(true);
        analysisRecy.setLayoutManager(new LinearLayoutManager(this));
        analysisRecy.setItemAnimator(new DefaultItemAnimator());
        analysisRecy.setAdapter(analysisAdapter);
        //图片选择的横向的recyclerView
        imageContentAdapter = new ActionBrightPointImageAdapterHolder(this, processImg, recyclerProImg.getWidth());
        recyclerProImg.setHasFixedSize(true);
        recyclerProImg.setLayoutManager(new LinearLayoutManager(this, LinearLayout.HORIZONTAL, false) {
            @Override
            public boolean canScrollHorizontally() {
                return false;
            }
        });
        recyclerProImg.setItemAnimator(new DefaultItemAnimator());
        recyclerProImg.setAdapter(imageContentAdapter);
        imageContentAdapter.setOnItemClickListener(this);
        //图片描述的纵向RecyclerView
        detailsAdapter = new ActionImageBrightPointProcessAdapterHolder(this, processStr);
        recyclerProTxt.setNestedScrollingEnabled(false);
        recyclerProTxt.setHasFixedSize(true);
        recyclerProTxt.setLayoutManager(new LinearLayoutManager(this));
        recyclerProTxt.setItemAnimator(new DefaultItemAnimator());
        recyclerProTxt.setAdapter(detailsAdapter);
    }

    private void initEditPager() {
        editPager.getLayoutParams().height = editPager.getWidth();
        targetAdapter = new EditContractPagerAdapter(this, editBitmaps);
        editPager.setAdapter(targetAdapter);
        circleIndicator.setViewPager(editPager);
        circleIndicator.setPadding(5, 5, 10, 15);
        NaizhuAILog.e("initEditPager完成");
    }

    private void initBaseData() {
        //模拟数据
//        makeVirtualData();
        scanDetailsBean = new ActionSubmitScanDetailsBean();
        editBitmaps = new ArrayList<>();
//        initErrorBitmap();
        filePaths = new ArrayList<>();
        analysisList = new ArrayList<>();
        processStr = new ArrayList<>();
        processImg = new ArrayList<>();
        imageDetails = new ActionSelectedProcessImageDetails();
    }

    private void initErrorBitmap() {
        editBitmaps.add(BitmapFactory.decodeResource(getResources(), R.mipmap.delete_fork));
    }

    //静态的模拟数据
    private void makeVirtualData() {
        editActivityBean = new ActionEditContractActivityBean();
        CompareImageBean compareBeans = new CompareImageBean();
        ImageBean before = new ImageBean();
        ImageBean after = new ImageBean();
        compareBeans.setBeforeImage(before);
        compareBeans.setAfterImage(after);
    }

    //从上个页面Rxbus获取数据
    private void getDataFromRx() {
//        shortToast("传输RX");
        RxBus.getDefault().toObservableSticky(ActionEditContractActivityBean.class).subscribe(new Action1<ActionEditContractActivityBean>() {
            @Override
            public void call(ActionEditContractActivityBean actionEditContractActivityBean) {
                editActivityBean = actionEditContractActivityBean;
                if (experience != null && editActivityBean != null) {
                    refreshData();
                }
            }
        });
    }

    //更新数据
    private void refreshData() {
        createTxtData();
        changeImageData();
        //展示合成图片的循环展示的图片集合
        createEditBitmap();
    }

    private void changeImageData() {
        List<SimpleKeyValueBean> showImage = new ArrayList<>();
        for (String img : processImg) {
            showImage.add(new SimpleKeyValueBean(ActionAddImageAdapterHolder.URL_NET_IMAGE, img));
        }
        imageDetails.setImageList(showImage);
    }

    private void createTxtData() {
        //改善title
        if (!TextUtils.isEmpty(editActivityBean.getSchemeName())) {
            changeData.setVisibility(View.VISIBLE);
            changeData.setText(editActivityBean.getSchemeName());
        } else
            changeData.setVisibility(View.GONE);
        //心得
        if (!TextUtils.isEmpty(editActivityBean.getReview())) {
            experience.setText(editActivityBean.getReview());
            reviewCaed.setVisibility(View.VISIBLE);
        } else
            reviewCaed.setVisibility(View.GONE);
        //数据结构体
        if (editActivityBean.getSelectedCompareData() != null && editActivityBean.getSelectedCompareData().size() > 0 && !TextUtils.isEmpty(editActivityBean.getSelectedCompareData().get(0).getPointId())) {
            ActionCompareDataBean compareDataBean = editActivityBean.getSelectedCompareData().get(0);
            compareDataCard.setVisibility(View.VISIBLE);
            //金額的占位String
            String valueNumber = getText(R.string.action_compare_data).toString();
//            String radiuNumber = getText(R.string.improve_ratio_data).toString();
            String moneyNumber = getText(R.string.improve_money_data).toString();
            String pre = compareDataBean.getbValue();
            String after = compareDataBean.getaValue();
            NaizhuAILog.e("pre=" + pre + ";after=" + after);

            String afterValue = String.format(valueNumber, after, compareDataBean.getUnit());
            aftData.setText(afterValue);
            if (!TextUtils.isEmpty(compareDataBean.getbFormula())) {
                bValueLayout.setVisibility(View.VISIBLE);
                beforeValueType.setText(compareDataBean.getbFormula());
            } else
                bValueLayout.setVisibility(View.GONE);
            if (!TextUtils.isEmpty(compareDataBean.getaFormula())) {
                aValueLayout.setVisibility(View.VISIBLE);
                afterValueType.setText(compareDataBean.getaFormula());
            } else
                aValueLayout.setVisibility(View.GONE);
            String preValue = String.format(valueNumber, pre, compareDataBean.getUnit());
            preData.setText(preValue);
//            proMoney.setText(String.format(moneyNumber, compareDataBean.getSimulatedAmount()));
            if (MathUtils.numberRadius(pre, after) != null)
                proRatio.setText(String.format("%s%s", MathUtils.numberRadius(pre, after), getString(R.string.percent)));
            else
                compareDataCard.setVisibility(View.GONE);
        } else
            compareDataCard.setVisibility(View.GONE);
        //问题分析过程
        analysisList.clear();
        analysisList.addAll(ListUtils.removeEmpty(editActivityBean.getThinkingDetail()));
        analysisAdapter.notifyDataSetChanged();
        if (analysisList.size() > 0) {
            analysisLayout.setVisibility(View.VISIBLE);
        } else
            analysisLayout.setVisibility(View.GONE);
        //问题过程图片以及文字详情
        processImg.clear();
        processImg.addAll(editActivityBean.getProcessImages());
        processStr.clear();
        processStr.addAll(ListUtils.removeEmpty(editActivityBean.getProcessDetail()));
        detailsAdapter.notifyDataSetChanged();
        imageContentAdapter.notifyDataSetChanged();
        if (processImg.size() > 0 || processStr.size() > 0) {
            detailLayout.setVisibility(View.VISIBLE);
        } else {
            detailLayout.setVisibility(View.GONE);
        }

    }

    //创建合成照片并且展示出来
    private void createEditBitmap() {
        finishMergeCount = 0;
        Observable.from(editActivityBean.getCompareImage())
                .subscribeOn(Schedulers.io())
                .map(new Func1<CompareImageBean, Bitmap>() {
                    @Override
                    public Bitmap call(CompareImageBean compareImageBean) {
                        NaizhuAILog.e("createEditBitmap_start");
                        return BitmapUtils.getComposeBitmapByUri(
                                compareImageBean.getBeforeImage().getImageUriOutput(),
                                compareImageBean.getAfterImage().getImageUriOutput(),
                                ActionScanDetailsViewActivity.this);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Bitmap>() {
                    @Override
                    public void onCompleted() {
                        editPager.post(new Runnable() {
                            @Override
                            public void run() {
                                //加载合成图片的循环列表
                                initEditPager();
                            }
                        });
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Bitmap bitmap) {
                        finishMergeCount++;
                        editBitmaps.add(bitmap);
                    }
                });
    }


    //确认并提交信息
    private void submitEditMessage(int type) {
        subMergeImage(type);
    }

    //提交合成的图片的信息
    private void subMergeImage(int type) {
        if (editActivityBean.getSelectedCompareData() != null && editActivityBean.getSelectedCompareData().size() > 0 && !TextUtils.isEmpty(editActivityBean.getSelectedCompareData().get(0).getPointId())) {
            scanDetailsBean.setChangeData(Collections.singletonList(editActivityBean.getSelectedCompareData().get(0)));
        }
        scanDetailsBean.setQuestionId(editActivityBean.getQuestionId());
        scanDetailsBean.setReview(editActivityBean.getReview());
        filePaths.clear();
        bitmapChangeCount = 0;
        Subscription uploadSub = Observable.from(editBitmaps)
                .subscribeOn(Schedulers.io())
                .map(new Func1<Bitmap, List<String>>() {
                    @Override
                    public List<String> call(Bitmap bitmap) {
                        String path = editActivityBean.getCompareImage().get(bitmapChangeCount).getBeforeImage().getPath();
                        bitmapChangeCount++;
                        File mergeFile = BitmapUtils.changeBitmap2File(bitmap, ActionScanDetailsViewActivity.this, path);
                        filePaths.add(mergeFile.getAbsolutePath());
                        return filePaths;
                    }
                }).filter(new Func1<List<String>, Boolean>() {
                    @Override
                    public Boolean call(List<String> strings) {
                        return strings.size() == editActivityBean.getCompareImage().size();
                    }
                }).flatMap(new Func1<List<String>, Observable<List<ImageBean>>>() {
                    @Override
                    public Observable<List<ImageBean>> call(List<String> strings) {
                        NaizhuAILog.e("flatMap(new Func1<List<String>");
                        return UploadImageApiStoreIml.getInstance().uploadImagesByUrl(strings);
                    }
                }).flatMap(new Func1<List<ImageBean>, Observable<List<ImageBean>>>() {
                    @Override
                    public Observable<List<ImageBean>> call(List<ImageBean> imageBeans) {
                        for (int index = 0; index < imageBeans.size(); index++) {
                            editActivityBean.getCompareImage().get(index).setMergeImage(imageBeans.get(index));
                            NaizhuAILog.e("onNext_url=" + imageBeans.get(index).getUrl());
                        }
                        List<String> afterImgPath = new ArrayList<>();
                        NaizhuAILog.e("afterImgPath.size=" + afterImgPath.size());
                        for (int index = 0; index < editActivityBean.getCompareImage().size(); index++) {
                            String filePath = FileUtils.getPath(getActivityContext(), editActivityBean.getCompareImage().get(index).getAfterImage().getImageUriInput());
                            NaizhuAILog.e("after.....image..path=" + filePath);
                            afterImgPath.add(filePath);
                        }
                        return UploadImageApiStoreIml.getInstance().uploadImagesByUrl(afterImgPath);
                    }
                }).subscribe(new Observer<List<ImageBean>>() {
                    @Override
                    public void onCompleted() {
                        hideWaitDialog();
                        NaizhuAILog.e("onCompleted");
                        switch (type) {
                            case TYPE_SUBMIT:
                                postActionScanDetailsData();
                                break;
                            case TYPE_THANK:
                                IntentUtils.startActivityWithObject(ThankSettingPagerActivity.SUBMIT_MAP_KEY, scanDetailsBean, getActivityContext(), ThankSettingPagerActivity.class);
                                break;
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        ApiException.showException(e, ActionScanDetailsViewActivity.this, true);
                    }

                    @Override
                    public void onNext(List<ImageBean> imageBeans) {
                        for (int index = 0; index < imageBeans.size(); index++) {
                            editActivityBean.getCompareImage().get(index).setAfterImage(imageBeans.get(index));
                            NaizhuAILog.e("onNext_url=" + imageBeans.get(index).getUrl());
                        }
                        scanDetailsBean.setChangeImages(editActivityBean.getCompareImage());
                    }
                });
        showWaitDiaLog(uploadSub);
    }

    private void postActionScanDetailsData() {
        Map<String, String> detailsMap = new HashMap<>();
        detailsMap.put(ActionSubmitScanDetailsBean.QUESTION_ID_KEY, scanDetailsBean.getQuestionId());
        detailsMap.put(ActionSubmitScanDetailsBean.REVIEW_KEY, scanDetailsBean.getReview());
        NaizhuAILog.e("getReview=" + scanDetailsBean.getReview());
        detailsMap.put(ActionSubmitScanDetailsBean.CHANGE_DATA_KEY, scanDetailsBean.getChangeData());
        NaizhuAILog.e("getChangeData=" + scanDetailsBean.getChangeData());
        detailsMap.put(ActionSubmitScanDetailsBean.CHANGE_IMAGE_KEY, scanDetailsBean.getChangeImages());
        NaizhuAILog.e("getChangeImages=" + scanDetailsBean.getChangeImages());
        Subscription submitSub = ActionManageApiStoreIml.getInstance().submitActionDetails(detailsMap).subscribe(submitObser);
        showWaitDiaLog(submitSub);
    }

    @Override
    public void onBackPressedWithoutDialog() {
        DialogUtils.showSureDialog(this, getString(R.string.lost_data), dialog -> finish());
    }

    private Observer<String> submitObser = new Observer<String>() {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            hideWaitDialog();
            NaizhuAILog.e("postActionScanDetailsData_Throwable e=" + e.getMessage());
            ApiException.showException(e, getActivityContext(), true);
        }

        @Override
        public void onNext(String s) {
            hideWaitDialog();
            if (ConstantsState.isResultOk(s)) {
                shortToast("提交成功");
                IntentUtils.startActivity(getActivityContext(), MainActivity.class);
//                ActivityStackManager.getInstance().killAllActivityExceptOne(MainActivity.class);
            } else
                shortToast("提交失败");
        }
    };

    @Override
    protected void onDestroy() {
        BitmapUtils.recycleBitmap(editBitmaps);
        super.onDestroy();
    }

    @OnClick({R.id.point_btn, R.id.thank_btn})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.point_btn:
                //bottom的确认提交
                submitEditMessage(TYPE_SUBMIT);
                break;
            case R.id.thank_btn:
                //跳转感谢信界面
                submitEditMessage(TYPE_THANK);
                break;
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_business_action_scan_detail_layout;
    }

    @Override
    public void onItemClick(View view, int position) {
        imageDetails.setPosition(position);
        imageDetails.setEdit(false);
        IntentUtils.startActivityWithObject(ActionShowChoseImageActivity.IMAGE_DATA_DETAILS, imageDetails, this, ActionShowChoseImageActivity.class);
    }

    //轮播图适配器
    private class EditContractPagerAdapter extends PagerAdapter {
        private BaseActivity mContext;
        private List<Bitmap> editBitmaps;

        EditContractPagerAdapter(BaseActivity context, List<Bitmap> editBitmaps) {
            this.mContext = context;
            this.editBitmaps = editBitmaps;
        }

        @Override
        public int getCount() {
            return editBitmaps.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            ImageView item = new ImageView(mContext);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            item.setLayoutParams(params);
            item.setScaleType(ImageView.ScaleType.FIT_XY);
            Bitmap bit = editBitmaps.get(position);
            if (!bit.isRecycled())
                item.setImageBitmap(bit);
//            item.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.mipmap.delete_fork));
            container.addView(item);
            item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    shortToast("點擊了=" + position);
                }
            });
            return item;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup collection, int position, @NonNull Object view) {
            collection.removeView((View) view);
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }
    }
}
